﻿Imports System.Text
Imports System.IO
Imports System.Text.RegularExpressions
Imports System.Data.EntityClient
Imports SecretaryToolData

Public Class frmMain

	Private WithEvents myUpdateChecker As New UpdateChecker
	Dim errorFileInfo As FileInfo

	Public Sub New()
		RemoveHandler AppDomain.CurrentDomain.UnhandledException, AddressOf UnhandledException
		AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf UnhandledException

		RemoveHandler Application.ThreadException, AddressOf ThreadException
		AddHandler Application.ThreadException, AddressOf ThreadException

		' This call is required by the designer.
		InitializeComponent()

		' Add any initialization after the InitializeComponent() call.

	End Sub

	Protected Overrides Sub Finalize()
		'if you don't remove the handlers you'll leak memory
		RemoveHandler AppDomain.CurrentDomain.UnhandledException, AddressOf UnhandledException
		RemoveHandler Application.ThreadException, AddressOf ThreadException

		MyBase.Finalize()
	End Sub

	Private Sub btnPublishers_Click(sender As System.Object, e As System.EventArgs) Handles btnPublishers.Click
		Dim frmPublishers As New frmPublishers
		frmPublishers.ShowDialog()

	End Sub

	Private Sub btnBackup_Click(sender As System.Object, e As System.EventArgs) Handles btnBackup.Click
		If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
			BackupDatabase(SaveFileDialog1.OpenFile)
		End If
	End Sub

	Public Shared Sub AutoBackupDatabase()
		If AutoBackupFile IsNot Nothing Then
			Try
				If AutoBackupFile.Exists Then
					File.Copy(AutoBackupFile.FullName, String.Format("{0}{1}", Regex.Replace(AutoBackupFile.FullName, String.Format("{0}$", AutoBackupFile.Extension), "").AppendFileDateExtension, AutoBackupFile.Extension))
				End If
				BackupDatabase(AutoBackupFile.Open(FileMode.Create))

			Catch ex As Exception
				MessageBox.Show("Automatic backup failed.", "Automatic Backup Failed", MessageBoxButtons.OK, MessageBoxIcon.Error)
			End Try
		End If
	End Sub

	Private Sub btnRestore_Click(sender As System.Object, e As System.EventArgs) Handles btnRestore.Click

		If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
			RestoreDatabase(OpenFileDialog1.OpenFile)

			InitializeFields()

			DisplayLastReportedDate()

		End If

	End Sub

	Private Sub frmMain_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
		AutoBackupDatabase()
	End Sub

	Private Sub frmMain_Load(sender As Object, e As System.EventArgs) Handles Me.Load
		DisplayLastReportedDate()

		If ConfigPropertyKeys.CongergationName = "" Then
			ConfigPropertyKeys.CongergationName = InputBox("What is the name of the congregation?", "Congregation Name Needed")
			If ConfigPropertyKeys.CongergationName = "" Then
				Me.Dispose()
			End If
		End If

		InitializeFields()

		Me.Text = String.Format("Secretary Tool v{0}", My.Application.Info.Version.ToString)

		'add code to start update checker on background thread

	End Sub

	Private Sub InitializeFields()
		lblCongregationName.Text = ConfigPropertyKeys.CongergationName
		lblAutoBackupLocation.Text = ConfigPropertyKeys.AutoBackupLocation.FullName
		txtS21LanguageCode.Text = ConfigPropertyKeys.S21Language
		numS21VerticalOffset.Value = ConfigPropertyKeys.S21VerticalOffset
	End Sub

	Private Sub DisplayLastReportedDate()
		lblReportLastSumitted.Text = If(ReportLastSubmitted = Date.MinValue, "Never", String.Format(ReportLastSubmitted, DateFormat.LongDate))
	End Sub

	Private Sub btnMarkReportAsSubmitted_Click(sender As System.Object, e As System.EventArgs) Handles btnMarkReportAsSubmitted.Click
		MarkReportAsSubmitted()
	End Sub

	Friend Sub MarkReportAsSubmitted()

		'backup before change
		AutoBackupDatabase()

		Dim currentReport As New MonthlyReportRecord(New VM_BranchReport)
		If Not currentReport.Save() Then
			Dim LastMonth As DateTime = DateTime.Now.AddMonths(-2)
			If MessageBox.Show(String.Format("Was this report for {0}, {1}?", LastMonth.ToString("MMM"), LastMonth.Year), "Last Months Report?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
				If Not currentReport.Save(LastMonth) Then
					MessageBox.Show("Save failed.", "Save Failed", MessageBoxButtons.OK, MessageBoxIcon.Error)
				End If
			Else
				'try saving as this month, buy forcing the month to overcome safeties in the save routine
				If Not currentReport.Save(LastMonth.AddMonths(-1)) Then
					MessageBox.Show("Save failed.", "Save Failed", MessageBoxButtons.OK, MessageBoxIcon.Error)
				End If
			End If
		End If

		'and after change
		AutoBackupDatabase()

		'Keys.ReportLastSubmitted = DateTime.UtcNow
		DisplayLastReportedDate()
	End Sub

	Private Sub btnEnterTime_Click(sender As System.Object, e As System.EventArgs) Handles btnEnterTime.Click
		Dim frmEnterTime As New frmEnterTime
		frmEnterTime.ShowDialog()
	End Sub

	Private Sub btnSetAutoBackupLocation_Click(sender As System.Object, e As System.EventArgs) Handles btnSetAutoBackupLocation.Click
		If FolderBrowserDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
			ConfigPropertyKeys.AutoBackupLocation = New DirectoryInfo(FolderBrowserDialog1.SelectedPath)
			lblAutoBackupLocation.Text = ConfigPropertyKeys.AutoBackupLocation.FullName
		End If
	End Sub

	Private Sub btnBranchReport_Click(sender As System.Object, e As System.EventArgs) Handles btnBranchReport.Click
		Dim frmBranchReport As New frmBranchReport
		frmBranchReport.Show()
	End Sub

	Private Sub btnCongregationAnalysis_Click(sender As System.Object, e As System.EventArgs) Handles btnCongregationAnalysis.Click
		Dim frmCongregationAnalysis As New frmCongregationAnalysis
		frmCongregationAnalysis.ShowDialog()
	End Sub

	Private Sub btnEmergencyContactInfo_Click(sender As System.Object, e As System.EventArgs) Handles btnEmergencyContactInfo.Click
		Dim frmEmergencyContact As New frmEmergencyContact
		frmEmergencyContact.ShowDialog()
	End Sub

	Private Sub btnAttendance_Click(sender As System.Object, e As System.EventArgs) Handles btnAttendance.Click
		Dim frmAttendance As New frmAttendance
		frmAttendance.ShowDialog()
	End Sub

	Private Sub btnMonthlyReports_Click(sender As System.Object, e As System.EventArgs) Handles btnMonthlyReports.Click
		Dim frmMonthlyReports As New frmMonthlyReports
		frmMonthlyReports.ShowDialog()
	End Sub

	Private Sub txtS21LanguageCode_TextChanged(sender As Object, e As System.EventArgs) Handles txtS21LanguageCode.TextChanged
		ConfigPropertyKeys.S21Language = txtS21LanguageCode.Text.ToUpper
	End Sub

	Private Sub numS21VerticalOffset_ValueChanged(sender As Object, e As System.EventArgs) Handles numS21VerticalOffset.ValueChanged
		ConfigPropertyKeys.S21VerticalOffset = numS21VerticalOffset.Value
	End Sub

	Private Sub btnGroups_Click(sender As System.Object, e As System.EventArgs) Handles btnGroups.Click
		Dim frmGroups As New frmGroups
		frmGroups.ShowDialog()
	End Sub

	Private Sub btnAttendanceReport_Click(sender As System.Object, e As System.EventArgs) Handles btnAttendanceReport.Click

	End Sub

	Private Sub btnCongregationStats_Click(sender As System.Object, e As System.EventArgs) Handles btnCongregationStats.Click
		Dim reportLocation As String = Reports.GenerateStatsReport.FullName
		If MessageBox.Show(String.Format("Report generated and saved at{0}{1}.{0}{0}Do you want to open it?", Environment.NewLine, reportLocation), "Report Successfully Generated", MessageBoxButtons.YesNo, MessageBoxIcon.Information) = Windows.Forms.DialogResult.Yes Then
			Process.Start(reportLocation)
		End If
	End Sub

	Private Sub btnAddEditMobileProviders_Click(sender As System.Object, e As System.EventArgs) Handles btnAddEditMobileProviders.Click
		Dim frmMobileProviders As New frmMobileProviders
		frmMobileProviders.ShowDialog()
	End Sub

	Private Sub btnEmailAndNotifications_Click(sender As System.Object, e As System.EventArgs) Handles btnEmailAndNotifications.Click
		Dim frmEmail As New frmEmail
		frmEmail.ShowDialog()
	End Sub

	Private Sub btnUpdateCards_Click(sender As System.Object, e As System.EventArgs) Handles btnUpdateCards.Click
		Dim reportLocation As String = Reports.GenerateUpdateCardsReport.FullName
		If MessageBox.Show(String.Format("Report generated and saved at{0}{1}.{0}{0}Do you want to open it?", Environment.NewLine, reportLocation), "Report Successfully Generated", MessageBoxButtons.YesNo, MessageBoxIcon.Information) = Windows.Forms.DialogResult.Yes Then
			Process.Start(reportLocation)
		End If
	End Sub

	Private Sub btnEnteredTime_Click(sender As System.Object, e As System.EventArgs) Handles btnEnteredTime.Click
		Dim reportLocation As String = Reports.GenerateUpdateCardsReport(True).FullName
		If MessageBox.Show(String.Format("Report generated and saved at{0}{1}.{0}{0}Do you want to open it?", Environment.NewLine, reportLocation), "Report Successfully Generated", MessageBoxButtons.YesNo, MessageBoxIcon.Information) = Windows.Forms.DialogResult.Yes Then
			Process.Start(reportLocation)
		End If
	End Sub

	Private Sub btnIndividualReports_Click(sender As System.Object, e As System.EventArgs) Handles btnIndividualReports.Click
		Dim frmIndividualReports As New frmIndividualReports
		frmIndividualReports.ShowDialog()
	End Sub

	Private Sub UpdateAvailable(NewVersion As String) Handles myUpdateChecker.UpdateStatus
		llblStatus.Text = "-> " & NewVersion
		llblStatus.Enabled = True
		llblStatus.Links.Add(New LinkLabel.Link(3, llblStatus.Text.Length, "https://secretarytool.codeplex.com/"))
	End Sub

	Private Sub llblStatus_LinkClicked(sender As Object, e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles llblStatus.LinkClicked
		Process.Start(e.Link.LinkData)
	End Sub

	Private Sub CheckErrorFound() Handles Me.Activated
		'check if there are errors that should be reported
		errorFileInfo = New FileInfo(Environment.ExpandEnvironmentVariables("%AppData%\SecretaryTool.exe\Log.txt"))
		If errorFileInfo.Exists Then
			Dim errorString As String = String.Format("Error Logged on {0}.", errorFileInfo.LastWriteTime)
			lblErrorDescription.Text = errorString
			pnlErrorFound.Visible = True
		Else
			pnlErrorFound.Visible = False
		End If
	End Sub

	Private Sub llblDeleteError_LinkClicked(sender As Object, e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles llblDeleteError.LinkClicked
		Try
			errorFileInfo.Delete()
			pnlErrorFound.Visible = False
		Catch ex As Exception

		End Try
	End Sub

	Private Sub llblReportError_LinkClicked(sender As Object, e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles llblReportError.LinkClicked
		Try
			Dim newMessage As New MailToLinkBuilder
			Dim subject As String = String.Empty
			Dim body As String = String.Empty

			Using errorLog As TextReader = File.OpenText(errorFileInfo.FullName)
				body = errorLog.ReadToEnd
			End Using

			newMessage.ToAddresses.Add("secretarytool@adservium.com")

			newMessage.Subject = "Error in Secretary Tool"
			newMessage.Body = body

			Process.Start(newMessage.GetMailToLink())
		Catch ex As Exception

		End Try
	End Sub

	Private Sub llblViewError_LinkClicked(sender As Object, e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles llblViewError.LinkClicked
		Process.Start(errorFileInfo.FullName)
	End Sub
End Class
